package com.freesky.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayUserDtbankcustChannelvoucherSendRequest;
import com.alipay.api.response.AlipayUserDtbankcustChannelvoucherSendResponse;
import com.freesky.biz.activity.domain.TAlipayCouponDetail;
import com.freesky.biz.activity.mapper.CouponDetailMapper;
import com.freesky.biz.citic.domain.TCiticNew;
import com.freesky.biz.external.service.*;
import com.freesky.biz.icbc.domain.TIntegralExchange;
import com.freesky.biz.icbc.domain.TIntegralPointSplit;
import com.freesky.biz.icbc.mapper.IntegralExchangeMapper;
import com.freesky.biz.icbc.mapper.LotteryPayMapper;
import com.freesky.biz.pay.config.AliPayConfiguration;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.config.Constant;
import com.freesky.common.constant.Constants;
import com.freesky.common.core.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 积分兑换服务（暂未切换过来）
 */
@Component("pointExchangeTask")
public class PointExchangeTask {

    /*
    private static final Logger logger = LoggerFactory.getLogger(PointExchangeTask.class);

    @Autowired
    private IntegralExchangeMapper integralExchangeMapper;

    @Autowired
    private MobileCmccService mobileCmccService;

    @Autowired
    private MobileJulivesService mobileJulivesService;

    @Autowired
    private MobileJuCaiService mobileJuCaiService;

    @Autowired
    private AliPayConfiguration aliPayConfiguration;

    @Autowired
    private CouponDetailMapper couponDetailMapper;

    @Autowired
    private SendAlarmService sendAlarmService;

    public void taskProcess() {
        List<TIntegralPointSplit> pointSplitModelList = integralExchangeMapper.loadIntegralMobileDetailList();
        for(TIntegralPointSplit pointSplitModel:pointSplitModelList) {
            TIntegralExchange pointMobileRechageModel = integralExchangeMapper.getPointRechageById(pointSplitModel.getOrderId());
            logger.info(JSON.toJSONString(pointMobileRechageModel));
            if (pointMobileRechageModel != null) {
                int nTotalCount = Integer.parseInt(pointMobileRechageModel.getTotalCount());
                int nSuccessCount = Integer.parseInt(pointMobileRechageModel.getSuccessCount());
                if (nSuccessCount >= nTotalCount) {
                    integralExchangeMapper.updateProcessedStatusById(pointSplitModel.getId(), "5");
                    sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL, "【异常】JOB-积分兑话费-多充",
                            "次数异常：" + JSON.toJSONString(pointMobileRechageModel));
                    continue;
                }
            }

            if(pointSplitModel.getQyId().equalsIgnoreCase("1")) {
                //检测次数是不是超过三次
                int nSendCount = integralExchangeMapper.getRechargeMobileLogCount(pointSplitModel.getId());
                if (nSendCount >= 3) {
                    integralExchangeMapper.updateProcessedStatusById(pointSplitModel.getId(), "5");
                    sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL, "【异常】JOB-积分兑话费-超过三次",
                            "次数【" + nSendCount + "】：" + JSON.toJSONString(pointSplitModel));
                    continue;
                }
            }
            integralExchangeMapper.updateProcessedStatusById(pointSplitModel.getId(),"1");

            processIntegral(pointSplitModel);
        }
    }

    public void processIntegral(TIntegralPointSplit pointSplitModel){

    }

    //移动充值
    public void sendMobileCmccRecharge(TIntegralPointSplit pointSplitModel){
        try{
            pointSplitModel.setLastReqId(SeqUtil.getSeqId());
            AjaxResult result = mobileCmccService.sendMobileRecharge(
                    pointSplitModel.getLastReqId(),
                    String.valueOf(pointSplitModel.getAmt()*10),
                    pointSplitModel.getMobile());

            pointSplitModel.setChannel("移动");
            if(result.isSuccess()) {
                pointSplitModel.setRespCode(Constants.SUCCESS);
                pointSplitModel.setRespMsg("充值成功");
                pointSplitModel.setProcessed("4");
                pointSplitModel.setOrderSn(pointSplitModel.getLastReqId());
                pointSplitModel.setState("1");
            } else {
                pointSplitModel.setRespCode(Constants.FAIL);
                pointSplitModel.setRespMsg(result.getMsg());
                pointSplitModel.setProcessed("3");
            }
            integralExchangeMapper.updatePointResultById(pointSplitModel);

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑话费-移动接口",ioe.getMessage());
        }
    }

    //智信
    public void sendMobileRechargeJulive(TIntegralPointSplit pointSplitModel){
        try{
            pointSplitModel.setLastReqId(SeqUtil.getSeqId());
            AjaxResult result = mobileJulivesService.sendMobileRecharge(
                    pointSplitModel.getLastReqId(),
                    String.valueOf(pointSplitModel.getAmt()),
                    pointSplitModel.getMobile());

            pointSplitModel.setChannel("智信");
            pointSplitModel.setRespCode(result.get("code").toString());
            pointSplitModel.setRespMsg(result.getMsg());
            if(result.isSuccess()) {
                String orderSn = result.get("data").toString();
                pointSplitModel.setOrderSn(orderSn);
                pointSplitModel.setProcessed("2");
            } else {
                pointSplitModel.setProcessed("3");
            }
            integralExchangeMapper.updatePointResultById(pointSplitModel);

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑话费-智信接口",ioe.getMessage());
        }
    }

    public void sendMobileRechargeJuCai(TIntegralPointSplit pointSplitModel){
        try{
            pointSplitModel.setLastReqId(SeqUtil.getSeqId());
            AjaxResult result = mobileJuCaiService.sendMobileRecharge(
                    pointSplitModel.getLastReqId(),
                    String.valueOf(pointSplitModel.getAmt()),
                    pointSplitModel.getMobile());
            pointSplitModel.setChannel("聚采");
            pointSplitModel.setRespCode(result.get("code").toString());
            pointSplitModel.setRespMsg(result.getMsg());

            if(result.isSuccess()){
                pointSplitModel.setRechargeId("");
                pointSplitModel.setProcessed("2");
            } else {
                pointSplitModel.setProcessed("3");
            }
            integralExchangeMapper.updatePointResultById(pointSplitModel);

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑话费-聚采接口",ioe.getMessage());
        }
    }

    //立减金信息
    public void sendCouponExchange(TIntegralPointSplit pointSplitModel){
        try{
            String stockId = "";
            String activityId = pointExchangeService.selectActivityIdByType(String.valueOf(pointSplitModel.getAmt()),
                    pointSplitModel.getType());

            List<ActivityRulesModel> activityRulesModelList = activityService.getActivityRulesByActivityId(
                    activityId);

            if(activityRulesModelList.size()<=0){
                logger.error("sendCoupon activity error:"+activityId);
                return;
            }

            ActivityRulesModel activityRulesModel = activityRulesModelList.get(0);
            int nCount = couponStocksService.getUseCouponByBusiId(pointSplitModel.getId());
            if(nCount<=0) {
                CouponsModel couponsModel = new CouponsModel();
                couponsModel.setOpenId(pointSplitModel.getOpenId());
                couponsModel.setId(SeqUtil.getSeqId());
                couponsModel.setAppId(Constant.APP_ID);
                couponsModel.setStockId(activityRulesModel.getStockId());
                couponsModel.setActivityId(activityId);
                couponsModel.setBusiId(pointSplitModel.getId());
                couponsModel.setMchId(activityRulesModel.getMchId()); //Constant.STOCK_CREATOR_MCHID，1273410801
                couponsModel.setAmt(String.valueOf(pointSplitModel.getAmt()));

                ResultModel resultModel = couponStocksService.grantCouponsOpenId(couponsModel);
                if (resultModel.getCode().equalsIgnoreCase(Constant.SUCCESS)) {
                    couponStocksService.addCouponDetail(couponsModel);
                    pointSplitModel.setOrderSn(couponsModel.getCouponId());
                    pointSplitModel.setProcessed("4");
                } else {
                    pointSplitModel.setProcessed("3");
                }
                pointSplitModel.setChannel("微信");
                pointSplitModel.setLastReqId(SeqUtil.getSeqId());
                pointExchangeService.updatePointResultById(pointSplitModel);
            }

            logger.info("sendCouponExchange sucess:"+JSON.toJSONString(pointSplitModel));

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑话费-立减金接口",ioe.getMessage());
        }
    }

    //支付宝通用红包
    public void sendAlipayCoupon(TIntegralPointSplit pointSplitModel){
        try{
            String activityId = pointExchangeService.selectActivityIdByType(String.valueOf(pointSplitModel.getAmt()),
                    pointSplitModel.getType());
            List<ActivityRulesModel> activityRulesModelList = activityService.getActivityRulesByActivityId(
                    activityId);

            if(activityRulesModelList.size()<=0){
                logger.error("sendAlipayCoupon activity error:"+activityId);
                return;
            }

            ActivityRulesModel activityRulesModel = activityRulesModelList.get(0);

            int nCount = couponStocksService.getUseAlipayCouponByBusiId(pointSplitModel.getId());
            if(nCount>0){
                logger.info("sendAlipayCoupon sucess:"+JSON.toJSONString(pointSplitModel));
                return;
            }

            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
            certAlipayRequest.setServerUrl(aliPayConfiguration.getGatewayUrl());
            certAlipayRequest.setAppId(aliPayConfiguration.getAppId());
            certAlipayRequest.setPrivateKey(aliPayConfiguration.getPrivateKey());
            certAlipayRequest.setFormat("json");
            certAlipayRequest.setCharset(aliPayConfiguration.getCharset());
            certAlipayRequest.setSignType(aliPayConfiguration.getSignType());
            certAlipayRequest.setCertPath(aliPayConfiguration.getAppCertPath());
            certAlipayRequest.setAlipayPublicCertPath(aliPayConfiguration.getAlipayCertPath());
            certAlipayRequest.setRootCertPath(aliPayConfiguration.getAlipayRootCertPath());
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

            AlipayUserDtbankcustChannelvoucherSendRequest request = new AlipayUserDtbankcustChannelvoucherSendRequest();

            request.setBizContent("{" +
                    "  \"phone_id\":\""+pointSplitModel.getMobile()+"\"," +
                    "  \"activity_id\":\""+activityRulesModel.getStockId()+"\"," +
                    "  \"out_biz_no\":\""+pointSplitModel.getId()+"\"" +
                    "}");


            // 支付宝通用红包Resp:{"activityId":"ACT190CCV00515644","activityOrderId":"20220324180321ACT09393CCV00051406428","body":"{\"alipay_user_dtbankcust_channelvoucher_send_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"activity_id\":\"ACT190CCV00515644\",\"activity_order_id\":\"20220324180321ACT09393CCV00051406428\",\"discount_threshold_amt\":1001,\"discount_type\":\"reduce\",\"discount_value\":1000,\"send_amount\":1000,\"send_status\":\"SUCCESS\",\"voucher_id\":\"202203240007300293240AZCWK1F\"},\"alipay_cert_sn\":\"a7456c1d07b0d38c65d5de409b519d6b\",\"sign\":\"Mp/agpDS5+HUChJcnUnGfiKJb970ydZYNFseFji2FhFAbRFIesJIMXwnaDnBI8vSzRlQjf7GRRDTPYJlWehVmD/XrPNpbSqJK0kmi8OGgBO9vAA8vI7liq8NkenOa7wEe1RqTzjiHIRI4BHoGOPTQiugOLoUpG9vQztcso6eQXr+gCBZkBcqi0GXVbr7137aZcYQ94juZI7UjES0GYOEUbjXq2gBik8cawpT0iTkWfQk1IwHQKQ5bcjC1L4eh11LMwbyHG4zXzJo1ZUnnbIH3NqemYSTtGqcYmpBfta7wkIw7O201NnogNywX6QJ3Ry9EJMJ3BsCR2ENZYhBoIhqqQ==\"}","code":"10000","discountThresholdAmt":1001,"discountType":"reduce","discountValue":1000,"errorCode":"10000","msg":"Success","params":{"biz_content":"{  \"user_id\":\"2088512933424935\",  \"activity_id\":\"ACT190CCV00515644\",  \"out_biz_no\":\"956578649744740352\"}"},"sendAmount":1000,"sendStatus":"SUCCESS","success":true,"voucherId":"202203240007300293240AZCWK1F"}
            logger.info("支付宝通用红包Req:"+request.getBizContent());
            AlipayUserDtbankcustChannelvoucherSendResponse response = alipayClient.certificateExecute(request);
            logger.info("支付宝通用红包Resp:"+JSON.toJSONString(response));

            if (response.isSuccess()){
                pointSplitModel.setOrderSn(response.getVoucherId());
                pointSplitModel.setProcessed("4");
            } else {
                pointSplitModel.setProcessed("3");
            }
            pointSplitModel.setChannel("支付宝");
            pointSplitModel.setLastReqId(SeqUtil.getSeqId());
            //pointExchangeService.updatePointResultById(pointSplitModel);
            pointExchangeService.updateAlipayResultById(pointSplitModel);

            if(response.isSuccess()){
                TAlipayCouponDetail alipayCouponModel = new TAlipayCouponDetail();
                alipayCouponModel.setId(SeqUtil.getSeqId());
                alipayCouponModel.setAppId(Constant.APP_ID);
                alipayCouponModel.setActivityId(response.getActivityId());
                alipayCouponModel.setActivityOrderId(response.getActivityOrderId());
                alipayCouponModel.setVoucherId(response.getVoucherId());
                alipayCouponModel.setAmt(String.valueOf(pointSplitModel.getAmt()));
                alipayCouponModel.setOpenId(pointSplitModel.getMobile());
                alipayCouponModel.setBusiId(pointSplitModel.getId());
                alipayCouponModel.setStatus("");
                couponDetailMapper.addAliCouponDetail(alipayCouponModel);
            }

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑话费-支付宝接口",ioe.getMessage());
        }
    }

    public void sendElectricCoupon(TIntegralPointSplit pointSplitModel){
        try{
            pointSplitModel.setLastReqId(SeqUtil.getSeqId());
            ResultModel resultModel = stateGridService.payOutMobile(pointSplitModel.getMobile(),
                    String.valueOf(pointSplitModel.getOriAmt()*200/100));
            pointSplitModel.setChannel("国网");
            pointSplitModel.setRespCode(resultModel.getCode());
            pointSplitModel.setRespMsg(resultModel.getMsg());
            if(resultModel.getCode().equalsIgnoreCase(Constant.SUCCESS)){
                pointSplitModel.setProcessed("2");
            } else {
                pointSplitModel.setProcessed("3");
            }
            pointExchangeService.updatePointResultById(pointSplitModel);
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑电费",ioe.getMessage());
        }
    }


    public void sendGiveCoupon(TIntegralPointSplit pointSplitModel){
        try{
            String activityId = "1829812521603829760";
            List<ActivityRulesModel> activityRulesModelList = activityService.getActivityRulesByActivityId(
                    activityId);

            if(activityRulesModelList.size()<=0){
                logger.error("sendCoupon activity error:"+activityId);
                return;
            }

            int nCount = couponStocksService.getUseCouponByBusiId(pointSplitModel.getId());
            if(nCount<=0) {
                for(ActivityRulesModel activityRulesModel : activityRulesModelList) {
                    CouponsModel couponsModel = new CouponsModel();
                    couponsModel.setOpenId(pointSplitModel.getOpenId());
                    couponsModel.setId(SeqUtil.getSeqId());
                    couponsModel.setAppId(Constant.APP_ID);
                    couponsModel.setStockId(activityRulesModel.getStockId());
                    couponsModel.setActivityId(activityId);
                    couponsModel.setBusiId(pointSplitModel.getId());
                    couponsModel.setMchId(activityRulesModel.getMchId());
                    couponsModel.setAmt(String.valueOf(activityRulesModel.getAmt()));

                    ResultModel resultModel = couponStocksService.grantCouponsOpenId(couponsModel);
                    if (resultModel.getCode().equalsIgnoreCase(Constant.SUCCESS)) {
                        couponStocksService.addCouponDetail(couponsModel);
                        pointSplitModel.setOrderSn(couponsModel.getCouponId());
                        pointSplitModel.setProcessed("4");
                    } else {
                        pointSplitModel.setProcessed("3");
                    }
                }

                pointSplitModel.setChannel("微信");
                pointSplitModel.setLastReqId(SeqUtil.getSeqId());
                pointExchangeService.updatePointResultById(pointSplitModel);
            }

            logger.info("sendCouponExchange sucess:"+JSON.toJSONString(pointSplitModel));

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑一赠一-立减金接口",ioe.getMessage());
        }
    }
     */
}
